<template>
  <div class="PersonMaintenance">
    <div class="list">
      <van-form validate-first>
        <div v-for="(item, index) in labelData" :key="index">
          <!-- <span style="color: #ff0000">*</span> -->
          <van-field v-if="!item.isSelect && !item.isTime" :readonly="item.isread" v-model="formData[item.key]" :label="item.label" :placeholder="'请填写' + item.label" />
          <div v-if="item.isSelect && !item.isTime">
            <div v-if="item.label !== '常住地址'">
              <van-field readonly clickable name="picker" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" @click="formData1[item.key1] = true" />
              <van-popup v-model="formData1[item.key1]" position="bottom" get-container="#popup">
                <van-picker show-toolbar :columns="formData2[item.key1]" value-key="DICNAME" @confirm="onConfirm1" @cancel="formData1[item.key1] = false" />
              </van-popup>
            </div>
            <span class="btn" v-if="item.label == '常住地址'">
              <van-field readonly clickable name="picker" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" @click="handleChange" />
              <van-popup v-model="IsShowAre" round position="bottom">
                <van-cascader v-model="cascaderValue" title="切换城市" :options="options" @close="closeA" @change="onChange" @finish="onFinish" />
              </van-popup>
            </span>
          </div>
          <div v-if="item.isTime">
            <van-field readonly clickable name="picker" @click="formData1[item.key1] = true" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" />
            <van-popup v-model="formData1[item.key1]" position="bottom">
              <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" @cancel="formData1[item.key1] = false" @confirm="onConfirm2" :min-date="minDate" :max-date="maxDate" />
            </van-popup>
          </div>
        </div>

        <div>
          <p style="color: #5d5d5d; padding: 10px 14px">
            <!-- <span style="color: #ff0000">*</span> -->
            请拍摄并上传本人正面照：
          </p>
          <div>
            <div style="width: 50%; float: left; text-align: center">
              <van-uploader
                v-model="fileList"
                accept="image/jpeg, image/png, image/jpg, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/pdf"
                :after-read="afterRead"
                :before-delete="delectFile"
                :max-count="1">
              </van-uploader>
              <p :style="{ fontSize: showEdition ? '12px' : '14px' }">本人正面照</p>
            </div>
          </div>
        </div>
      </van-form>
    </div>
    <div class="footer">
      <van-button type="info" size="normal" style="padding: 6px" @click="getinsertDataView('修改')">提交</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.PersonMaintenance {
  height: 100vh;
  overflow-y: auto;
  padding: 6px;
  position: relative;
  .list {
    height: 84vh;
    overflow-y: auto;
  }
  .footer {
    position: absolute;
    height: 6vh;
    // bottom: 18px;
    left: 50%;
    top: 94%;
    transform: translate(-50%, -50%);
  }
}
</style>

<script>
import {
  LoadGridData,
  QuerySignCallback,
  GetAdministrative,
  getDatalistForTree,
  zhejiangHouseArtisan,
  zhejiangHouseArtisanUp,
  dataqueryFile,
  selectListByIds,
  ossUploadFiles,
  osspreviewFiles,
  FileServerProxy
} from '../../utils/api'
import { idCard } from '../../utils/idCard'
export default {
  data() {
    return {
      formData: {
        artisanName: '',
        artisanSex: '',
        artisanEducation: '',
        artisanBirthdate: '',
        contactAddress: '',
        artisanSkill: '',
        idCard: '',
        phone: '',
        bookNumber: '',
        workYear: '',
        fileid: ''
      },
      show: false,
      actions: [
        {
          name: '选项'
        },
        {
          name: '选项'
        },
        {
          name: '选项',
          subname: '描述信息',
          openType: 'share'
        }
      ],
      cascaderValue: '',
      options: [
        {
          text: '杭州市',
          value: '441300000000',
          children: []
        }
      ],
      IsShowAre: false,
      showEdition: true,
      currentDate: new Date(),
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2089, 12, 1),
      isread: false,
      formData1: {
        sex: false,
        artisanEducation: false,
        CSNY: false
      },
      formData2: {
        sex: [
          {
            DICNAME: '男',
            key: '1'
          },
          {
            DICNAME: '女',
            key: '0'
          }
        ],
        artisanEducation: [
          {
            DICNAME: '初中及以下',
            key: 'artisanEducation'
          },
          {
            DICNAME: '高中',
            key: 'artisanEducation'
          },
          {
            DICNAME: '大专',
            key: 'artisanEducation'
          },
          {
            DICNAME: '本科',
            key: 'artisanEducation'
          },
          {
            DICNAME: '研究生',
            key: 'artisanEducation'
          }
        ]
      },
      fileList: [],
      url: '',
      baseUrl: window.g.BaseURL,
      qitaShow: false,
      labelData: [
        {
          label: '姓名',
          key: 'artisanName',
          isSelect: false,
          isread: true
        },
        {
          label: '身份证号',
          key: 'idCard',
          isread: true
        },
        {
          label: '性别',
          key: 'artisanSex',
          key1: 'sex',
          isSelect: false,
          isread: true
        },
        {
          label: '出生年月',
          key: 'artisanBirthdate',
          key1: 'CSNY',
          isTime: false,
          isread: true
        },
        {
          label: '联系电话',
          key: 'phone',
          isread: true
        },
        {
          label: '证书编号',
          key: 'bookNumber',
          isread: true
        },
        {
          label: '技能',
          key: 'isSkill',
          isread: true
        },
        {
          label: '文化程度',
          key: 'artisanEducation',
          key1: 'artisanEducation',
          isSelect: true,
          isread: false
        },
        {
          label: '常住地址',
          key: 'contactAddress',
          isSelect: true,
          isread: false
        },
        {
          label: '从业年限(仅限数字)',
          key: 'setYeare',
          isread: false
        },
        {
          label: '其他技能',
          key: 'otherSkill',
          isread: this.qitaShow
        }
      ]
    }
  },
  mounted() {
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: '工匠个人信息维护'
      })
        .then((res) => {})
        .catch((err) => {})
    }
    this.getGJInformcion()
    this.getXianOpenDataView()
  },
  methods: {
    //获取上传的图片回显
    async getPhoto(data1) {
      this.fileList = []
      // let data = res.data.data[0]
      this.url = 'api/upload/oss/preview?fileId=' + data1
      this.fileList.push({
        url: this.baseUrl + 'api/upload/oss/preview?fileId=' + data1,
        isImage: true
      })
    },
    onClose() {
      this.setData({ show: false })
    },

    onSelect(event) {
      console.log(event.detail)
    },
    //获取工匠信息
    async getGJInformcion() {
      debugger
      let data = {
        accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
        cityCode: '441300000000',
        id: window.localStorage.getItem('DanDianid') || ''
      }
      const res = await zhejiangHouseArtisan(data)
      if (!res.data.data) {
        // this.$toast.success('系统未查询到您的工匠信息，请联系区县建设部门录入!')
        this.$confirm({
          title: '提示',
          message: '系统未查询到您的工匠信息，请联系区县建设部门录入',
          btn: {
            okText: '确定',
            cancelText: '取消'
          }
        })
          .then(() => {
            this.$router.push({
              path: '/ZLJIndex'
            })
          })
          .catch(() => {
            this.$router.push({
              path: '/ZLJIndex'
            })
          })
      } else {
        this.formData = res.data.data
        try {
          let newArr = this.formData.isSkill != null ? this.formData.isSkill.split(',') : []
          if (newArr.length > 0) {
            newArr.forEach((item) => {
              if (item == '其他') {
                this.qitaShow = true
              }
            })
          }
        } catch (e) {
          console.log(e)
        }
        if (this.formData.fileid) {
          this.getPhoto(this.formData.fileid)
        }
      }
      console.log(this.qitaShow)
      const str = idCard(window.localStorage.getItem('DanDianid'), 2)
      console.log(str, '===================')
      this.formData.artisanSex = str
    },
    onConfirm1(value) {
      this.formData1[value.key] = false
      this.formData[value.key] = value.DICNAME
    },
    getXianOpenDataView: async function (data = '330000000000') {
      this.options = []
      const res = await getDatalistForTree(data)
      res.data.data.forEach((item) => {
        this.options.push({
          text: item.cityname,
          value: item.citycode,
          children: []
        })
      })
      console.log(this.options, 'hezhilong')
      // this.options = res.data.data
    },
    handleChange() {
      this.IsShowAre = true
    },
    onChange({ value, selectedOptions, tabIndex }) {
      if (selectedOptions[tabIndex].children.length == 0 && tabIndex < 2) {
        this.getXZQH(value, selectedOptions, tabIndex)
      }
      this.onFinish({ value, selectedOptions, tabIndex })
    },
    closeA() {
      this.IsShowAre = false
    },
    onFinish({ value, selectedOptions, tabIndex }) {
      this.formData.contactAddress = selectedOptions.map((option) => option.text).join('/')
      this.areaCode = selectedOptions.map((option) => option.value)
      this.areaCode.length == 3 ? (this.IsShowAre = false) : ''
    },
    getXZQH: async function (value, selectedOptions, tabIndex) {
      var res = await GetAdministrative(value)
      selectedOptions[tabIndex].children = []
      if (res.data.data.length > 0) {
        res.data.data.forEach((element) => {
          let obj = {
            text: element.cityname,
            value: element.citycode
          }
          if (tabIndex < 1) {
            obj['children'] = []
          }
          selectedOptions[tabIndex].children.push(obj)
        })
      }
    },
    onConfirm2(value) {
      this.formData.CSNY = this.dateFormat(value)
      this.formData1.CSNY = false
    },
    // 格式化日期
    dateFormat(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      let time = `${year}-${month}-${day}`
      return time
    },
    isEmpty(obj) {
      if (typeof obj === 'undefined' || obj === null || obj === '' || obj === 'null') return true
      return false
    },
    preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (this.isEmpty(data[item])) {
          delete data[item]
        }
      })
      return data
    },
    async getinsertDataView(data) {
      this.formData = this.preProcessData(this.formData)
      //需要先判断技能中是否有其他字段 如果有并且更新了需要同步更新workerType
      try {
        var newArr = this.formData.workerType == null ? [] : this.formData.workerType.split(',')
        var xiabiao = newArr.indexOf('其他')
        if (xiabiao > -1) newArr[xiabiao] = this.formData.otherSkill
      } catch (err) {
        console.log(err)
      }
      //   if(newArr[newArr.length-1]!=this.formData.otherSkill){
      //     newArr[newArr.length-1] = this.formData.otherSkill
      //   }
      this.formData.workerType = newArr.toString()
      var newobj = this.formData
      console.log(newobj, 'klkopl')
      if (data == '修改') {
        //只能修改
        let data1 = {
          accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
          appKey: '6738b790-69e8-11ec-a673-6805cab640a0',
          cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
          id: window.localStorage.getItem('DanDianid') || '',
          houseArtisanInfo: newobj
        }
        const res = await zhejiangHouseArtisanUp(data1)
        if (res.data.code == 200 && res.data.msg == '成功') {
          this.$toast.success('更新成功!')
          this.$router.push({
            path: '/ZLJIndex'
          })
        } else {
          this.$toast.success('更新失败!')
        }
      }
    },
    afterRead(file) {
      this.getFileServerUpload(file.file, 'scsfz')
    },
    getFileServerUpload: async function (file, data) {
      let formData = new FormData()
      formData.append('files', file)
      formData.append('path', 'gj')
      formData.append('groupName', '工匠信息')
      formData.append('toGroupGuid', '123')
      const res = await ossUploadFiles(formData)
      let data2 = res.data.data
      console.log(data2, 'hezhilong')
      this.formData.fileid = data2[0].id
      if (this.formData.fileid) {
        this.$toast.success('上传成功!')
      }
    },
    delectFile: async function (file) {
      debugger
      try {
        let fileguid = ''
        if (file.ROW_GUID) {
          fileguid = file.ROW_GUID
        } else {
          fileguid = this.formData.fileid
        }
        this.url = ''
        console.log(fileguid, 'dkjfhui')
        if (fileguid) {
          let params = {
            accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
            cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
            params: {
              fileGuid: fileguid,
              token: window.localStorage.getItem('token')
            }
          }
          const res = await FileServerProxy(params)
          let data = JSON.parse(res.data.data).Success
          if (data) {
            this.$toast.success('删除成功!')
          }
        }
      } catch (err) {
        this.$toast.success('删除成功!')
      }
    }
  }
}
</script>
